﻿using System.Drawing;
using System.Drawing.Imaging;
using QRCoder;

namespace Lg.Core
{
    public class ImgHandler
    {
        private readonly bool isSession = false;
        private readonly string[] codes = { "A", "1", "B", "2", "C", "3", "D", "4", "E", "5", "F", "6", "7", "G", "8", "H", "9", "I", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
        private string vCode = "";//随机数

        /// <summary>
        /// 无参构造，默认处理方式为 自动生成6位验证码，数字和字母组合，不添加进session["CaptchaCode"]
        /// </summary>
        public ImgHandler()
        {

        }
        /// <summary>
        /// 指定是否将生成的验证号添加至session["CaptchaCode"]
        /// </summary>
        /// <param name="isSession"></param>
        public ImgHandler(bool isSession)
        {
            this.isSession = isSession;
        }

        public ImgHandler(bool isSession, string code)
        {
            this.isSession = isSession;
            this.vCode = code;
        }

        public ImgHandler(bool isSession, string code, string[] codes)
        {
            this.isSession = isSession;
            this.vCode = code;
            this.codes = codes;
        }

        #region 获取验证码
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns>验证码图片png byte[]</returns>
        public byte[] GetCaptchaCode()
        {
            System.Random rand = new();
            //生成随机数
            if (string.IsNullOrEmpty(vCode))
            {
                for (int i = 0; i < 6; i++)
                {
                    vCode += codes[rand.Next(codes.Length)];
                }
            }
            //开始画图
            using System.Drawing.Bitmap img = new (90, 34);
            Graphics g = Graphics.FromImage(img);
            g.Clear(Color.White);

            for (int i = 0; i < 100; i++)
            {
                //画背景线条
                Pen p = new (Color.FromArgb(rand.Next()));
                var x1 = rand.Next(100);
                var x2 = rand.Next(30);
                var y1 = rand.Next(30);
                var y2 = rand.Next(30);
                g.DrawLine(p, x1, x2, y1, y2);
            }

            //画文字
            g.DrawString(vCode, new Font("Consolas", 16f, FontStyle.Italic), Brushes.Black, 5, 5);

            //画图片的前景干扰点
            for (int i = 0; i < 500; i++)
            {
                int x = rand.Next(img.Width);
                int y = rand.Next(img.Height);
                img.SetPixel(x, y, Color.FromArgb(rand.Next()));
            }

            //画图片的边框线
            g.DrawRectangle(new Pen(Color.Silver), 0, 0, img.Width - 1, img.Height - 1);

            MemoryStream MStream = new ();
            img.Save(MStream, ImageFormat.Png);
            return MStream.ToArray();
        }
        #endregion

        

        /// <summary>
        /// 根据base64字符串返回一个封装好的GDI+位图。
        /// </summary>
        /// <param name="base64string">可转换成位图的base64字符串。</param>
        /// <returns>Bitmap对象。</returns>
        public static Bitmap GetImageFromBase64(string base64string)
        {
            byte[] b = Convert.FromBase64String(base64string);

            using MemoryStream ms = new(b);
            Bitmap bitmap = new (ms);
            return bitmap;
        }

        /// <summary>
        /// 将图片转换成base64字符串。
        /// </summary>
        /// <param name="imagefile">需要转换的图片文件。</param>
        /// <returns>base64字符串。</returns>
        public static string GetBase64FromImage(string imagefile, int w, int h)
        {
            string strbaser64 = "";

            System.Drawing.Image image = System.Drawing.Image.FromFile(imagefile);
            int outWidth = image.Width;
            int outHeight = image.Height;
            if (w == h)
            {
                if (image.Width > image.Height)
                {
                    outWidth = image.Height;
                }
                else
                {
                    outHeight = image.Width;
                }
            }
            else
            {
                if (image.Width > w && image.Height > h)
                {
                    double o_rate = (double)Math.Round((double)image.Width / (double)image.Height, 2);
                    double n_rate = (double)Math.Round((double)w / (double)h, 2);
                    if (o_rate > n_rate)
                    {
                        outWidth = (int)Math.Ceiling(image.Height * n_rate);
                        outHeight = image.Height;
                    }
                    else
                    {
                        outHeight = (int)Math.Ceiling(image.Width / n_rate);
                        outWidth = image.Width;
                    }
                }

            }
            System.Drawing.Image newimg = new System.Drawing.Bitmap(w, h);
            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(newimg))
            {
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                g.DrawImage(image, new System.Drawing.Rectangle(0, 0, w, h), new System.Drawing.Rectangle(0, 0, outWidth, outHeight), System.Drawing.GraphicsUnit.Pixel);
                g.Dispose();
            }
            try
            {
                Bitmap bmp = new (newimg);
                using MemoryStream ms = new();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                strbaser64 = Convert.ToBase64String(arr);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }

            return strbaser64;
        }
    }
}
